package com.ruoyi.resume.utils;

import com.ruoyi.resume.domain.model.Category;
import com.ruoyi.resume.mapper.CategoryMapper;

import java.util.HashSet;
import java.util.Set;

public class RecursiveCategoryFinder {
    private final CategoryMapper categoryMapper;
    private final Set<Integer> visit;

    public RecursiveCategoryFinder(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
        this.visit = new HashSet<>();
    }

    public Integer findValidAlgorithmCategoryId(Integer categoryId) {
        while (categoryId != null) {
            // 检查访问记录
            if (visit.contains(categoryId)) {
                System.out.println("跳过已访问的 Category ID：" + categoryId);
                return null;
            }

            // 将当前 categoryId 加入访问记录
            visit.add(categoryId);

            // 查询当前分类
            Category category = categoryMapper.findCategoryById(categoryId);
            if (category == null) {
                throw new RuntimeException("未找到 categoryId 对应的分类，Category ID：" + categoryId);
            }

            // 如果算法地址不为空，返回当前分类 ID
            if (category.getAlgorithmIdentifier() != null && !category.getAlgorithmIdentifier().isEmpty()) {
                return category.getId();
            }

            // 否则继续查找父级分类
            categoryId = category.getParentId();
        }

        // 如果遍历到顶层还没找到，抛出异常
        throw new RuntimeException("未找到有效的算法地址");
    }
}

